/* 引入Vue */
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

/* 注册Vuex */
Vue.use(Vuex)

/* 状态 */
const state = {
  userinfo: JSON.parse(localStorage.getItem('userinfo')),
  userList: [],
}
/* mutations 主要用来操作 state*/
const mutations = {
  //保存用户数据
  save_userinfo(state, userinfo) {
    //先把数据存入本地储存
    localStorage.setItem("userinfo", JSON.stringify(userinfo))
    //再更新数据
    state.userinfo = userinfo;
  },
  //获取全局的所有用户数据
  get_userList(state, userlist) {
    state.userList = userlist;
  }
}

//定义actions 异步的 主要是commit mutations 由mutations来改变状态
const actions = {
  get_userList({
    commit
  }) {
    return new Promise((resolve, reject) => {
      axios.get('/api/getuserlist')
        .then((result) => {
          /* console.log('获取全局的所有用户数据', result.data); */
          commit('get_userList', result.data)
          resolve();
        }).catch((err) => {
          console.log(err);
        });
    });
  }
}

//过滤年龄大于23岁的定义为VIP用户
const getters = {
  vipUsers: state => state.userList.filter(vip => vip.age > 23)
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
